package yzserver.sx4a.user;

import com.sitech.ibnms.util.DesEncrypterIsmp;
import com.sitech.portal.system.dao.ISysDeptDao;
import com.sitech.portal.system.dao.ISysLogInmsgDao;
import com.sitech.portal.system.dao.ISysUserRoleDao;
import com.sitech.portal.system.dao.ISysWorkGroupDao;
import com.sitech.portal.system.domain.TblSYS_DEPT;
import com.sitech.portal.system.domain.TblSYS_LOGINMSG;
import com.sitech.portal.system.domain.TblSYS_USER_ROLE;
import org.apache.commons.lang.StringUtils;
import yzserver.sx4a.RetTools;
import yzserver.sx4a.dao.IDepartmentDao;
import yzserver.sx4a.dao.IUserDao;
import yzserver.sx4a.domain.UserDomain;
import yzserver.sx4a.form.Ret;
import yzserver.sx4a.form.User;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: andrew
 * Date: 14-8-15
 * Time: 上午10:14
 * To change this template use File | Settings | File Templates.
 */
public class Sx4aUserImpl implements Sx4aUser {
    private ISysLogInmsgDao sysLogInmsgDao;
    private ISysUserRoleDao sysUserRoleDao;
    private IUserDao userDao;
    private ISysWorkGroupDao sysWorkGroupDao;

    public void setSysWorkGroupDao(ISysWorkGroupDao sysWorkGroupDao) {
        this.sysWorkGroupDao = sysWorkGroupDao;
    }

    public void setSysUserRoleDao(ISysUserRoleDao sysUserRoleDao) {
        this.sysUserRoleDao = sysUserRoleDao;
    }

    public void setSysLogInmsgDao(ISysLogInmsgDao sysLogInmsgDao) {
        this.sysLogInmsgDao = sysLogInmsgDao;
    }

    public void setUserDao(IUserDao userDao) {
        this.userDao = userDao;
    }


    @Override
    public User selUser(String uid) {
        UserDomain domain = userDao.selUser(uid);
        if(domain!=null){
            List<TblSYS_USER_ROLE> roles =sysUserRoleDao.findRoleListByUserId(uid);
            if(roles!=null&&roles.size()>0){
                StringBuffer sbrole = new StringBuffer("");
                for(TblSYS_USER_ROLE role:roles){
                    sbrole.append(role.getROLE_ID()+",");
                }
                sbrole.delete(sbrole.length() - 1, sbrole.length());
                domain.setROLE(sbrole.toString());
            }
            List<HashMap> orglist = userDao.selUserOrgRel(uid);
            if(orglist!=null&&orglist.size()>0){
                StringBuffer sborg = new StringBuffer("");
                for(HashMap map:orglist){
                    sborg.append(map.get("ORGID")+"@");
                }
                sborg.delete(sborg.length() - 1, sborg.length());
                domain.setORG(sborg.toString());
            }
            List<HashMap> posJoblist = userDao.selUserPosJobRel(uid);
            if(posJoblist!=null&&posJoblist.size()>0){
                StringBuffer sbpos = new StringBuffer("");
                StringBuffer sbjob = new StringBuffer("");
                for(HashMap map:posJoblist){
                    sbpos.append(map.get("POSITIONID")+"@");
                    sbjob.append(map.get("JOBID")+"@");
                }
                sbpos.delete(sbpos.length() - 1, sbpos.length());
                sbjob.delete(sbjob.length() - 1, sbjob.length());
                domain.setJOB(sbjob.toString());
                domain.setPOSITION(sbpos.toString());
            }
            User user = new User(domain);
            return user;
        }else{
            return null;
        }

    }

    @Override
    public List selAllUser(String uid) {
        List<UserDomain> userDomains = new ArrayList<UserDomain>();
        List  userList = new ArrayList();
        if("all".equalsIgnoreCase(uid)){ // all为接口约定的固定值
            userDomains = userDao.selAllUser(uid);
            if(userDomains!=null){
                for (int i = 0; i <userDomains.size(); i++) {
                    User user = new User(userDomains.get(i));
                    userList.add(user);
                }
            }
        }
        return userList;
    }

    @Override
    public Ret addUser(User user) {
        //----------------4a表-----------
        //添加账号
        String pst = user.getPosition();
        String role = user.getRole();
        String org = user.getOrg();
        String job = user.getJob();

        String[] psts = new String[]{};
        String[] roles = new String[]{};
        String[] orgs = new String[]{};
        String[] jobs = new String[]{};

        if(StringUtils.isNotEmpty(pst)){
            psts = pst.split("@");
        }
        if(StringUtils.isNotEmpty(role)){
            roles = role.split(",");
        }
        if(StringUtils.isNotEmpty(org)){
            orgs = org.split("@");
        }
        if(StringUtils.isNotEmpty(job)){
            jobs = job.split("@");
        }
        try {
            DesEncrypterIsmp encrypter = new DesEncrypterIsmp();
            if(user.getPwd()==null||user.getPwd().equals("")){
                user.setPwd("12345678");
            }
            user.setPwd(encrypter.encrypt(user.getPwd()));
            userDao.addUser(new UserDomain(user));
            for (int i = 0; i < orgs.length; i++) {//账户与组织关系
                userDao.addUserOrgRel(user.getUid(),orgs[i],i==0?"1":"0");
            }
            for (int i = 0; i < jobs.length; i++) {//账户与岗位职责关系
                userDao.addUserPosJobRel(user.getUid(),psts[i],jobs[i],i+"");
            }
        } catch (Exception e) {
            return RetTools.getRet("创建账号失败", e);
        }
        String updatePortal = System.getProperty("updatePortal");
        if("true".equals(updatePortal)){
            //--------portal表--------------------t
            TblSYS_LOGINMSG tblSYS_LOGINMSG = new TblSYS_LOGINMSG();
            tblSYS_LOGINMSG.setLOGIN_ID(user.getUid());
            tblSYS_LOGINMSG.setNAME(user.getCn());
            tblSYS_LOGINMSG.setLOGIN_PASSWD(user.getPwd());
            tblSYS_LOGINMSG.setEMAIL_ADDR(user.getMail());
            tblSYS_LOGINMSG.setLOGIN_PHONE(user.getMobile());
            if(orgs!=null&&orgs.length>0){
                tblSYS_LOGINMSG.setDEPT_ID(orgs[0]);
            }
            tblSYS_LOGINMSG.setLOCAL_PHONE(user.getMobile());
            tblSYS_LOGINMSG.setUSER_ID_UP(user.getUid());
            tblSYS_LOGINMSG.setLOCKSTATE(user.getEnable());
            try {
                sysLogInmsgDao.add(tblSYS_LOGINMSG);//账号
                if(roles!=null&&roles.length>0){
                    sysUserRoleDao.add(tblSYS_LOGINMSG, roles, tblSYS_LOGINMSG);//角色
                }
                if(psts!=null&&psts.length>0){
                    for (int i = 0; i <psts.length ; i++) {
                        sysWorkGroupDao.insertUserToWorkGroup(tblSYS_LOGINMSG.getLOGIN_ID(), psts[i]);//岗位
                    }
                }
            } catch (Exception e) {
                return RetTools.getRet("创建账号失败", e);
            }
        }
        return RetTools.getRet("创建帐号成功", null);
    }

    @Override
    public Ret editUser(User user) {
        //----------------41表-----------
        String pst = user.getPosition();
        String role = user.getRole();
        String org = user.getOrg();
        String job = user.getJob();

        String[] psts = new String[]{};
        String[] roles = new String[]{};
        String[] orgs = new String[]{};
        String[] jobs = new String[]{};

        if(StringUtils.isNotEmpty(pst)){
            psts = pst.split("@");
        }
        if(StringUtils.isNotEmpty(role)){
            roles = role.split(",");
        }
        if(StringUtils.isNotEmpty(org)){
            orgs = org.split("@");
        }
        if(StringUtils.isNotEmpty(job)){
            jobs = job.split("@");
        }
        try {
            userDao.delUserPosJobRel(user.getUid());
            userDao.delUserOrgRel(user.getUid());

            userDao.editUser(new UserDomain(user));
            for (int i = 0; i < orgs.length; i++) {//账户与组织关系
                userDao.addUserOrgRel(user.getUid(),orgs[i],i==0?"1":"0");
            }
            for (int i = 0; i < jobs.length; i++) {//账户与岗位职责关系
                userDao.addUserPosJobRel(user.getUid(),psts[i],jobs[i],i+"");
            }
        } catch (Exception e) {
            return RetTools.getRet("修改账号失败", e);
        }
        String updatePortal = System.getProperty("updatePortal");
        if("true".equals(updatePortal)){
            //--------portal表--------------------t
            TblSYS_LOGINMSG tblSYS_LOGINMSG = new TblSYS_LOGINMSG();
            tblSYS_LOGINMSG.setLOGIN_ID(user.getUid());
            tblSYS_LOGINMSG.setNAME(user.getCn());
            if(StringUtils.isNotEmpty(user.getPwd())){
                DesEncrypterIsmp encrypter = new DesEncrypterIsmp();
                tblSYS_LOGINMSG.setLOGIN_PASSWD(encrypter.encrypt(user.getPwd()));
            }
            tblSYS_LOGINMSG.setEMAIL_ADDR(user.getMail());
            tblSYS_LOGINMSG.setLOGIN_PHONE(user.getMobile());
            if(psts!=null&&psts.length>0){
                tblSYS_LOGINMSG.setDEPT_ID(psts[0]);
            }
            tblSYS_LOGINMSG.setLOCAL_PHONE(user.getMobile());
            tblSYS_LOGINMSG.setUSER_ID_UP(user.getUid());
            tblSYS_LOGINMSG.setLOCKSTATE(user.getEnable());
            try {
                sysUserRoleDao.deleteByUserId(new String[]{user.getUid()});
                sysWorkGroupDao.deleteWorkGroupByUser(user.getUid());

                sysLogInmsgDao.update(tblSYS_LOGINMSG);
                sysUserRoleDao.add(tblSYS_LOGINMSG, roles, tblSYS_LOGINMSG);//角色
                if(psts!=null&&psts.length>0){
                    for (int i = 0; i <psts.length ; i++) {
                        sysWorkGroupDao.insertUserToWorkGroup(tblSYS_LOGINMSG.getLOGIN_ID(), psts[i]);//岗位
                    }
                }
            } catch (Exception e) {
                return RetTools.getRet("修改账号失败", e);
            }
        }

        return RetTools.getRet("修改帐号成功", null);

    }

    @Override
    public Ret operationUserPwd(String uid, String pwd) {
        DesEncrypterIsmp encrypter = new DesEncrypterIsmp();

        try {
            userDao.operationUserPwd(uid, encrypter.encrypt(pwd));
        } catch (Exception e) {
            return RetTools.getRet("修改密码失败", e);
        }
        String updatePortal = System.getProperty("updatePortal");
        if("true".equals(updatePortal)){
            //--------portal表--------------------
            HashMap pwdMap = new HashMap();
            pwdMap.put("userNewPassword",encrypter.encrypt(pwd));
            pwdMap.put("userId", uid);
            try {
                sysLogInmsgDao.updatePassword(pwdMap);
            } catch (Exception e) {
                return RetTools.getRet("修改账号失败", e);
            }
        }
        return RetTools.getRet("修改密码成功", null);
    }

    @Override
    public Ret operationUser(String uid, String enable) {
        try {
            userDao.operationUser(uid, enable);
        } catch (Exception e) {
            return RetTools.getRet(enable == "0" ? "启用" : "禁用" + "帐号失败", e);
        }
        String updatePortal = System.getProperty("updatePortal");
        if("true".equals(updatePortal)){
            //--------portal表--------------------
            try {
                if("0".equals(enable)){
                    sysLogInmsgDao.cancelfrozen(new String[]{uid});
                }else if("1".equals(enable)){
                    sysLogInmsgDao.frozenUser(new String[]{uid});
                }
            } catch (Exception e) {
                return RetTools.getRet(enable == "0" ? "启用" : "禁用" + "帐号失败", e);
            }
        }

        return RetTools.getRet(enable == "0" ? "启用" : "禁用" + "帐号成功", null);
    }

    @Override
    public Ret delUser(String uid) {
        try {
            userDao.delUser(uid);
            userDao.delUserPosJobRel(uid);
            userDao.delUserOrgRel(uid);
        } catch (Exception e) {
            return RetTools.getRet("删除帐号失败", e);
        }
        String updatePortal = System.getProperty("updatePortal");
        if("true".equals(updatePortal)){
            //--------portal表--------------------
            try {
                sysLogInmsgDao.delete(new String[]{uid});
                sysUserRoleDao.deleteByUserId(new String[]{uid});
                sysWorkGroupDao.deleteWorkGroupByUser(uid);

            } catch (Exception e) {
                return RetTools.getRet("删除帐号失败", e);
            }
        }
        return RetTools.getRet("删除帐号成功", null);
    }

    @Override
    public Ret sendAllUser(List<User> userlist) {
     if(userlist!=null){
         for (int z = 0; z <userlist.size() ; z++) {
             //----------------4a表-----------
             //添加账号
             User user = userlist.get(z);
             String pst = user.getPosition();
             String role = user.getRole();
             String org = user.getOrg();
             String job = user.getJob();

             String[] psts = new String[]{};
             String[] roles = new String[]{};
             String[] orgs = new String[]{};
             String[] jobs = new String[]{};

             if(StringUtils.isNotEmpty(pst)){
                 psts = pst.split("@");
             }
             if(StringUtils.isNotEmpty(role)){
                 roles = role.split(",");
             }
             if(StringUtils.isNotEmpty(org)){
                 orgs = org.split("@");
             }
             if(StringUtils.isNotEmpty(job)){
                 jobs = job.split("@");
             }
             try {
                 DesEncrypterIsmp encrypter = new DesEncrypterIsmp();
                 if(user.getPwd()==null||user.getPwd().equals("")){
                     user.setPwd("12345678");
                 }
                 user.setPwd(encrypter.encrypt(user.getPwd()));
                 userDao.addUser(new UserDomain(user));
                 for (int i = 0; i < orgs.length; i++) {//账户与组织关系
                     userDao.addUserOrgRel(user.getUid(),orgs[i],i==0?"1":"0");
                 }
                 for (int i = 0; i < jobs.length; i++) {//账户与岗位职责关系
                     userDao.addUserPosJobRel(user.getUid(),psts[i],jobs[i],i+"");
                 }
             } catch (Exception e) {
                 return RetTools.getRet("创建账号失败", e);
             }
             String updatePortal = System.getProperty("updatePortal");
             if("true".equals(updatePortal)){
                 //--------portal表--------------------t
                 TblSYS_LOGINMSG tblSYS_LOGINMSG = new TblSYS_LOGINMSG();
                 tblSYS_LOGINMSG.setLOGIN_ID(user.getUid());
                 tblSYS_LOGINMSG.setNAME(user.getCn());
                 tblSYS_LOGINMSG.setLOGIN_PASSWD(user.getPwd());
                 tblSYS_LOGINMSG.setEMAIL_ADDR(user.getMail());
                 tblSYS_LOGINMSG.setLOGIN_PHONE(user.getMobile());
                 if(orgs!=null&&orgs.length>0){
                     tblSYS_LOGINMSG.setDEPT_ID(orgs[0]);
                 }
                 tblSYS_LOGINMSG.setLOCAL_PHONE(user.getMobile());
                 tblSYS_LOGINMSG.setUSER_ID_UP(user.getUid());
                 tblSYS_LOGINMSG.setLOCKSTATE(user.getEnable());
                 try {
                     sysLogInmsgDao.add(tblSYS_LOGINMSG);//账号
                     if(roles!=null&&roles.length>0){
                        sysUserRoleDao.add(tblSYS_LOGINMSG, roles, tblSYS_LOGINMSG);//角色
                     }
                     if(psts!=null&&psts.length>0){
                         for (int i = 0; i <psts.length ; i++) {
                             sysWorkGroupDao.insertUserToWorkGroup(tblSYS_LOGINMSG.getLOGIN_ID(), psts[i]);//岗位
                         }
                     }
                 } catch (Exception e) {
                     return RetTools.getRet("创建账号失败", e);
                 }
             }

         }
     }
        return RetTools.getRet("创建帐号成功", null);
    }


}
